package com.yzt.message.custom;

import android.content.Context;
import android.media.AudioManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.text.TextUtilsCompat;

import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.config.AppConfig;
import com.yzt.zhuju.db.VoiceMsgIdHelper;
import com.yzt.zhuju.widget.GenderAgeView;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.message.R;

import java.util.List;
import java.util.Locale;

import io.rong.imkit.model.UiMessage;
import io.rong.imkit.widget.adapter.IViewProviderListener;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.common.NetUtils;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.HQVoiceMessage;

/**
 * 功能：语音的自定义消息
 */
public class RxHQVoiceMessageItemProvider extends CustomBaseMessageItemProvider<HQVoiceMessage> {

    public RxHQVoiceMessageItemProvider() {
        mConfig.showReadState = true;
        mConfig.showContentBubble = false;
    }

    @Override
    protected io.rong.imkit.widget.adapter.ViewHolder onCreateMessageContentViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_voice_message_item_provider, viewGroup, false);
        return new ViewHolder(view.getContext(), view);
    }

    @Override
    protected void bindMessageContentViewHolder(io.rong.imkit.widget.adapter.ViewHolder viewHolder, io.rong.imkit.widget.adapter.ViewHolder parentHolder, HQVoiceMessage content, UiMessage uiMessage, int position, List<UiMessage> list, IViewProviderListener<UiMessage> listener) {

        ViewHolder holder = (ViewHolder) viewHolder;

        holder.layoutGroup.setVisibility(View.GONE);
        if (uiMessage.getConversationType() == Conversation.ConversationType.GROUP) {
            String extra = content.getExtra();
            JSONObject json = JSONObject.parseObject(extra);
            if (json != null) {
                try {
                    int age = json.getInteger("age");
                    int gender = json.getInteger("gender");
                    int competence = json.getInteger("competence");
                    holder.viewGender.setUserInfo(gender, age);
                    if (competence > 0) {
                        holder.ivPosition.setImageResource(competence == 1 ? R.mipmap.icon_zuzhang : R.mipmap.icon_fuzuzhang);
                        holder.ivPosition.setVisibility(View.VISIBLE);
                    } else if (competence == -1){
                        holder.ivPosition.setImageResource(R.mipmap.icon_tourist);
                        holder.ivPosition.setVisibility(View.VISIBLE);
                    } else {
                        holder.ivPosition.setVisibility(View.GONE);
                    }
                    holder.layoutGroup.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            LinearLayout.LayoutParams groupLayoutParams = (LinearLayout.LayoutParams) holder.layoutGroup.getLayoutParams();
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.rcLayout.getLayoutParams();
            if (uiMessage.getMessageDirection() == Message.MessageDirection.SEND) {
                groupLayoutParams.gravity = Gravity.END;
                layoutParams.gravity = Gravity.END;
            } else {
                groupLayoutParams.gravity = Gravity.START;
                layoutParams.gravity = Gravity.START;
            }
        } else {
            holder.layoutGroup.setVisibility(View.GONE);
        }

        boolean isSender = uiMessage.getMessage().getMessageDirection().equals(Message.MessageDirection.SEND);

        //国际化
        if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == 1) {
            holder.mVoiceRightTimeTv.setText(String.format("\"%s", content.getDuration()));
            holder.mVoiceLeftTimeTv.setText(String.format("\"%s", content.getDuration()));
        } else {
            holder.mVoiceRightTimeTv.setText(String.format("%s\"", content.getDuration()));
            holder.mVoiceLeftTimeTv.setText(String.format("%s\"", content.getDuration()));
        }

        if (isSender) {//发送者
            setMessageExtra(uiMessage);
            holder.mVoiceLeftLayout.setVisibility(View.GONE);
            holder.mFromVoiceLayout.setVisibility(View.VISIBLE);
        } else {//接收
            holder.mVoiceLeftLayout.setVisibility(View.VISIBLE);
            holder.mFromVoiceLayout.setVisibility(View.GONE);
           // MakeMoneyManager.action(viewHolder.itemView, content.getExtra());
        }

        setLayout(holder.getContext(),holder,uiMessage);
    }

    private void setMessageExtra(UiMessage uiMessage){
        RongIMClient.getInstance().setMessageExtra(uiMessage.getMessageId(), "1", new RongIMClient.ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    @Override
    protected boolean onItemClick(io.rong.imkit.widget.adapter.ViewHolder viewHolder, HQVoiceMessage content, UiMessage uiMessage, int position, List<UiMessage> list, IViewProviderListener<UiMessage> listener) {
        if (listener != null) {
            playHQVoiceMessage((ViewHolder) viewHolder,uiMessage);
            listener.onViewClick(-7, uiMessage);
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected boolean isMessageViewType(MessageContent messageContent) {
        return messageContent instanceof HQVoiceMessage;
    }

    @Override
    public Spannable getSummarySpannable(Context context, HQVoiceMessage hqVoiceMessage) {
        return new SpannableString(context.getString(R.string.rc_message_content_voice));
    }

    private static class ViewHolder extends io.rong.imkit.widget.adapter.ViewHolder {
        private final LinearLayout mVoiceLeftLayout;
        private final RelativeLayout mToVoiceLayout;
        private final ImageView mVoiceLeftAnimIv;
        private final TextView mVoiceLeftTimeTv;
        private final ImageView mRcVoiceUnread;
        private final ImageView mRcVoiceDownloadError;

        private final RelativeLayout mFromVoiceLayout;
        private final TextView mVoiceRightTimeTv;
        private final ImageView mVoiceRightAnimIv;

        View layoutGroup;
        TextView tvNickname;
        GenderAgeView viewGender;
        ImageView ivPosition;

        LinearLayout rcLayout;

        public ViewHolder(Context context, View view) {
            super(context, view);

            this.mVoiceLeftLayout = view.findViewById(R.id.voice_left_layout);
            this.mToVoiceLayout = view.findViewById(R.id.to_voice_layout);
            this.mVoiceLeftAnimIv = view.findViewById(R.id.voice_left_anim_iv);
            this.mVoiceLeftTimeTv = view.findViewById(R.id.voice_left_time_tv);
            this.mRcVoiceUnread = view.findViewById(R.id.rc_voice_unread);
            this.mRcVoiceDownloadError = view.findViewById(R.id.rc_voice_download_error);

            this.mFromVoiceLayout = view.findViewById(R.id.from_voice_layout);
            this.mVoiceRightTimeTv = view.findViewById(R.id.voice_right_time_tv);
            this.mVoiceRightAnimIv = view.findViewById(R.id.voice_right_anim_iv);

            this.layoutGroup = view.findViewById(R.id.layout_group);
            this.tvNickname = view.findViewById(R.id.tv_nickname);
            this.viewGender = view.findViewById(R.id.view_gender);
            this.ivPosition = view.findViewById(R.id.iv_position);

            this.rcLayout = view.findViewById(R.id.rc_layout);
        }
    }

    public void addHearVoiceTimes() {
//        BizLayer.getInstance().getMessageModule().addHearVoiceTimes(ConversationCache.getInstance().getUserId(), new AresSubscriber<IntimateNumBean>() {
//            @Override
//            protected void onSuccess(IntimateNumBean intimate) {
//                ConversationCache.getInstance().setCanHearVoiceTimes(intimate.getCanHearVoiceTimes());
//                ConversationCache.getInstance().setUnlock(intimate.isUnlock());
//                ConversationCache.getInstance().setCanSendVoice(intimate.isCanSendVoice());
//            }
//        });
    }

    private void playHQVoiceMessage(ViewHolder holder,UiMessage message) {
        holder.mRcVoiceUnread.setVisibility(View.GONE);
        currentVolume(holder.getContext());
        String extra = message.getExtra();
        if (TextUtils.isEmpty(extra) || !TextUtils.equals(extra, "1")) {
            addHearVoiceTimes();
            VoiceMsgIdHelper.getInstance(AppConfig.context).insertVoicerHistory(String.valueOf(message.getMessageId()));
        }

        setMessageExtra(message);
    }

    public void currentVolume(Context context) {
        AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (currentVolume < 5) {
            ToastUtil.showMessage(context.getString(R.string.adjust_volume));
        }
    }

    private void setLayout(Context context, ViewHolder holder, UiMessage message) {
        boolean playing = message.isPlaying();

        HQVoiceMessage content = (HQVoiceMessage) message.getContent();
        if (message.getMessageDirection() == Message.MessageDirection.SEND) {
            initLayoutWidth(content.getDuration(), holder.mFromVoiceLayout);
            holder.mVoiceRightAnimIv.setImageResource(R.mipmap.icon_voice_rong_default_right);
            if (playing) {
                ImageLoadUtil.load(context,R.mipmap.gif_voice_rong_right,holder.mVoiceRightAnimIv);
            } else {
                ImageLoadUtil.load(context,R.mipmap.icon_voice_rong_default_right,holder.mVoiceRightAnimIv);
            }
        } else {
            initLayoutWidth(content.getDuration(), holder.mToVoiceLayout);
            holder.mRcVoiceDownloadError.setVisibility(View.GONE);
            if (((HQVoiceMessage) message.getContent()).getLocalPath() != null) {
                holder.mRcVoiceDownloadError.setVisibility(View.GONE);
            } else if (!NetUtils.isNetWorkAvailable(context)) {
                holder.mRcVoiceDownloadError.setVisibility(View.VISIBLE);
            }
            if (!message.getReceivedStatus().isListened() && ((HQVoiceMessage) message.getContent()).getLocalPath() != null) {
                holder.mRcVoiceUnread.setVisibility(View.VISIBLE);
            } else {
                holder.mRcVoiceUnread.setVisibility(View.GONE);
            }
            if (playing) {
                ImageLoadUtil.load(context,R.mipmap.gif_voice_rong_left,holder.mVoiceLeftAnimIv);
            } else {
                ImageLoadUtil.load(context,R.mipmap.icon_voice_rong_default_left,holder.mVoiceLeftAnimIv);
            }
        }
    }

    public void initLayoutWidth(int duration, RelativeLayout layout) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layout.getLayoutParams();
        params.height = DisplayUtils.dp2px(40);
        if (duration <= 20) {
            params.width = DisplayUtils.dp2px(100);
        } else if (duration <= 40) {
            params.width = DisplayUtils.dp2px(145);
        } else {
            params.width = DisplayUtils.dp2px(175);
        }
        layout.setLayoutParams(params);
    }
}

